import urllib.request as r
import urllib.parse as p
import json
import time
while True:
    test=input('请输入要翻译的内容(输入q!退出程序):')
    if test == 'q!':
        break
    url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    #浏览器伪装
    #head={}
    #head['User-Agent']='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0'


    data={}
    data['i']=test
    data['from']='AUTO'
    data['to']='AUTO'
    data['smartresult']='dict'
    data['client']='fanyideskweb'
    data['salt']='1525597081004'
    data['sign']='72c67277875a8b7cb354241245fad44a'
    data['doctype']='json'
    data['version']='2.1'
    data['keyfrom']='fanyi.web'
    data['action']='FY_BY_REALTIME'
    data['typoResult']='false'
    data=p.urlencode(data).encode('utf-8')

    req=r.Request(url,data)
    html_info=r.urlopen(req)
    #html中的.decode('utf-8')在windows当中可以不用写啦 但是在别的系统当中就需要啦
    html=html_info.read().decode('utf-8')

    target=json.loads(html)
    ttest=target['translateResult'][0][0]['tgt']
    print('翻译的结果为:',ttest)
    time.sleep(5)

